<template>
  <div class="death-registration">
    <!-- 功能切换 -->
    <div class="function-selector">
      <a-radio-group v-model:value="activeFunction" button-style="solid" size="large">
        <a-radio-button value="list">死亡记录</a-radio-button>
        <a-radio-button value="register">死亡登记</a-radio-button>
        <a-radio-button value="statistics">死因统计</a-radio-button>
      </a-radio-group>
    </div>

    <!-- 死亡记录列表 -->
    <div v-if="activeFunction === 'list'" class="death-records">
      <a-card title="死亡记录管理" class="records-card">
        <template #extra>
          <a-space>
            <a-input-search v-model:value="searchKeyword" placeholder="搜索姓名或死因" style="width: 250px" @search="handleSearch" />
            <a-select v-model:value="deathCauseFilter" placeholder="死因筛选" style="width: 150px" @change="handleFilterChange">
              <a-select-option value="all">全部死因</a-select-option>
              <a-select-option value="natural">自然死亡</a-select-option>
              <a-select-option value="accident">意外死亡</a-select-option>
              <a-select-option value="disaster">自然灾害</a-select-option>
              <a-select-option value="war">战争伤亡</a-select-option>
              <a-select-option value="plague">瘟疫死亡</a-select-option>
            </a-select>
          </a-space>
        </template>

        <a-table :columns="deathColumns" :data-source="filteredDeathRecords" :loading="loading" :pagination="pagination" row-key="id" class="death-table">
          <template #bodyCell="{ column, record }">
            <!-- 姓名列 -->
            <template v-if="column.key === 'name'">
              <a-space>
                <a-avatar size="small">
                  {{ record.name?.charAt(0) }}
                </a-avatar>
                <span>{{ record.name }}</span>
              </a-space>
            </template>

            <!-- 死亡信息 -->
            <template v-else-if="column.key === 'deathInfo'">
              <a-space direction="vertical" size="small">
                <div>{{ record.deathDate }} {{ record.deathTime }}</div>
                <div>{{ record.deathLocation }}</div>
              </a-space>
            </template>

            <!-- 死因 -->
            <template v-else-if="column.key === 'cause'">
              <a-space direction="vertical" size="small">
                <a-tag :color="getDeathCauseColor(record.deathCause)">
                  {{ deathCauses[record.deathCause]?.name || record.deathCause }}
                </a-tag>
                <span class="specific-cause">{{ record.specificCause }}</span>
              </a-space>
            </template>

            <!-- 遗言 -->
            <template v-else-if="column.key === 'lastWords'">
              <div class="last-words">
                {{ record.lastWords || '-' }}
              </div>
            </template>

            <!-- 状态 -->
            <template v-else-if="column.key === 'status'">
              <a-tag :color="record.documentStatus === 'completed' ? 'green' : 'orange'">
                {{ record.documentStatus === 'completed' ? '已完成' : '处理中' }}
              </a-tag>
            </template>

            <!-- 操作 -->
            <template v-else-if="column.key === 'action'">
              <a-space>
                <a-button type="link" size="small" @click="viewDetails(record)"> 详情 </a-button>
                <a-button type="link" size="small" @click="editRecord(record)"> 编辑 </a-button>
                <a-button type="link" size="small" @click="printCertificate(record)"> 打印证明 </a-button>
              </a-space>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>

    <!-- 死亡登记 -->
    <div v-if="activeFunction === 'register'" class="death-register">
      <a-row :gutter="[24, 24]">
        <!-- 基本信息 -->
        <a-col :xs="24" :lg="12">
          <a-card title="基本信息" class="register-card">
            <a-form :model="registerForm" layout="vertical">
              <a-form-item label="选择人员" required>
                <a-select v-model:value="registerForm.lifeRecordId" placeholder="选择要登记死亡的人员" show-search :filter-option="filterOption" @change="handlePersonSelect">
                  <a-select-option v-for="person in alivePersons" :key="person.id" :value="person.id"> {{ person.name }} - {{ person.location }} </a-select-option>
                </a-select>
              </a-form-item>

              <div v-if="selectedPerson" class="selected-person">
                <a-descriptions :column="1" size="small">
                  <a-descriptions-item label="姓名">{{ selectedPerson.name }}</a-descriptions-item>
                  <a-descriptions-item label="年龄">{{ selectedPerson.currentAge }}岁</a-descriptions-item>
                  <a-descriptions-item label="天定寿命">{{ selectedPerson.destinedLifespan }}岁</a-descriptions-item>
                  <a-descriptions-item label="居住地">{{ selectedPerson.location }}</a-descriptions-item>
                </a-descriptions>
              </div>

              <a-form-item label="死亡日期" required>
                <a-date-picker v-model:value="registerForm.deathDate" placeholder="选择死亡日期" style="width: 100%" />
              </a-form-item>

              <a-form-item label="死亡时间" required>
                <a-time-picker v-model:value="registerForm.deathTime" placeholder="选择死亡时间" format="HH:mm" style="width: 100%" />
              </a-form-item>

              <a-form-item label="死亡地点" required>
                <a-input v-model:value="registerForm.deathLocation" placeholder="请输入死亡地点" />
              </a-form-item>
            </a-form>
          </a-card>
        </a-col>

        <!-- 死因信息 -->
        <a-col :xs="24" :lg="12">
          <a-card title="死因信息" class="register-card">
            <a-form :model="registerForm" layout="vertical">
              <a-form-item label="死因分类" required>
                <a-select v-model:value="registerForm.deathCause" placeholder="选择死因分类" @change="handleCauseChange">
                  <a-select-option v-for="(cause, key) in deathCauses" :key="key" :value="key">
                    {{ cause.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>

              <a-form-item label="具体死因" required v-if="registerForm.deathCause">
                <a-select v-model:value="registerForm.specificCause" placeholder="选择具体死因">
                  <a-select-option v-for="subcategory in deathCauses[registerForm.deathCause]?.subcategories || []" :key="subcategory" :value="subcategory">
                    {{ subcategory }}
                  </a-select-option>
                </a-select>
              </a-form-item>

              <a-form-item label="目击者人数">
                <a-input-number v-model:value="registerForm.witnesses" :min="0" :max="100" style="width: 100%" />
              </a-form-item>

              <a-form-item label="报告人">
                <a-input v-model:value="registerForm.reportedBy" placeholder="请输入报告人" />
              </a-form-item>

              <a-form-item label="备注">
                <a-textarea v-model:value="registerForm.notes" placeholder="请输入备注信息" :rows="3" />
              </a-form-item>
            </a-form>
          </a-card>
        </a-col>

        <!-- 遗言遗愿 -->
        <a-col :xs="24">
          <a-card title="遗言遗愿" class="register-card">
            <a-form :model="registerForm" layout="vertical">
              <a-form-item label="遗言内容">
                <a-textarea v-model:value="registerForm.lastWords" placeholder="请记录逝者的遗言" :rows="4" />
              </a-form-item>

              <a-form-item>
                <a-space>
                  <a-button type="primary" @click="submitDeathRecord" :loading="submitting"> 提交登记 </a-button>
                  <a-button @click="resetForm"> 重置表单 </a-button>
                  <a-button @click="saveAsDraft"> 保存草稿 </a-button>
                </a-space>
              </a-form-item>
            </a-form>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 死因统计 -->
    <div v-if="activeFunction === 'statistics'" class="death-statistics">
      <a-row :gutter="[24, 24]">
        <!-- 死因分布 -->
        <a-col :xs="24" :lg="12">
          <a-card title="死因分布" class="statistics-card">
            <div class="cause-distribution">
              <div v-for="(cause, key) in deathCauses" :key="key" class="cause-item">
                <div class="cause-header">
                  <span class="cause-name">{{ cause.name }}</span>
                  <span class="cause-count">{{ deathStatistics[key] || 0 }}人</span>
                </div>
                <a-progress :percent="getPercentage(deathStatistics[key] || 0)" :stroke-color="getDeathCauseColor(key)" :show-info="false" />
              </div>
            </div>
          </a-card>
        </a-col>

        <!-- 月度统计 -->
        <a-col :xs="24" :lg="12">
          <a-card title="月度死亡统计" class="statistics-card">
            <div class="monthly-stats">
              <div ref="monthlyChart" style="width: 100%; height: 300px"></div>
            </div>
          </a-card>
        </a-col>

        <!-- 详细统计表 -->
        <a-col :xs="24">
          <a-card title="详细统计" class="statistics-card">
            <a-table :columns="statisticsColumns" :data-source="statisticsData" :pagination="false" size="small">
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'percentage'"> {{ record.percentage }}% </template>
                <template v-else-if="column.key === 'trend'">
                  <a-tag :color="record.trend > 0 ? 'red' : record.trend < 0 ? 'green' : 'blue'">
                    {{ record.trend > 0 ? '↑' : record.trend < 0 ? '↓' : '→' }}
                    {{ Math.abs(record.trend) }}%
                  </a-tag>
                </template>
              </template>
            </a-table>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 详情对话框 -->
    <a-modal v-model:open="showDetailModal" title="死亡记录详情" width="800px" :footer="null">
      <DeathRecordDetail :record="selectedRecord" @close="showDetailModal = false" />
    </a-modal>

    <!-- 编辑对话框 -->
    <a-modal v-model:open="showEditModal" title="编辑死亡记录" width="900px" :footer="null">
      <EditDeathRecordForm :record="selectedRecord" @success="handleEditSuccess" @cancel="showEditModal = false" />
    </a-modal>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import * as echarts from 'echarts'
import { useLifeDeathStore } from '@/stores/lifeDeath'
import DeathRecordDetail from './DeathRecordDetail.vue'
import EditDeathRecordForm from './EditDeathRecordForm.vue'

// Store
const lifeDeathStore = useLifeDeathStore()

// 响应式数据
const activeFunction = ref('list')
const searchKeyword = ref('')
const deathCauseFilter = ref('all')
const showDetailModal = ref(false)
const showEditModal = ref(false)
const selectedRecord = ref(null)
const submitting = ref(false)
const monthlyChart = ref(null)

// 登记表单
const registerForm = ref({
  lifeRecordId: null,
  deathDate: null,
  deathTime: null,
  deathLocation: '',
  deathCause: '',
  specificCause: '',
  witnesses: 1,
  reportedBy: '家属',
  lastWords: '',
  notes: ''
})

const selectedPerson = ref(null)

// 表格列定义
const deathColumns = [
  {
    title: '姓名',
    key: 'name',
    width: 120
  },
  {
    title: '死亡信息',
    key: 'deathInfo',
    width: 180
  },
  {
    title: '死因',
    key: 'cause',
    width: 150
  },
  {
    title: '遗言',
    key: 'lastWords',
    width: 200
  },
  {
    title: '目击者',
    dataIndex: 'witnesses',
    key: 'witnesses',
    width: 80
  },
  {
    title: '状态',
    key: 'status',
    width: 100
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right'
  }
]

const statisticsColumns = [
  {
    title: '死因类型',
    dataIndex: 'type',
    key: 'type'
  },
  {
    title: '死亡人数',
    dataIndex: 'count',
    key: 'count'
  },
  {
    title: '占比',
    key: 'percentage'
  },
  {
    title: '趋势',
    key: 'trend'
  }
]

// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true
})

// 计算属性
const loading = computed(() => lifeDeathStore.loading)
const deathCauses = computed(() => lifeDeathStore.deathCauses)
const deathStatistics = computed(() => lifeDeathStore.deathStatistics)

const alivePersons = computed(() => lifeDeathStore.lifeRecords.filter((record) => record.status === 'alive'))

const filteredDeathRecords = computed(() => {
  let records = lifeDeathStore.filteredDeathRecords

  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    records = records.filter((record) => record.name.toLowerCase().includes(keyword) || record.specificCause.toLowerCase().includes(keyword) || record.deathLocation.toLowerCase().includes(keyword))
  }

  if (deathCauseFilter.value !== 'all') {
    records = records.filter((record) => record.deathCause === deathCauseFilter.value)
  }

  pagination.value.total = records.length
  return records
})

const statisticsData = computed(() => {
  const total = Object.values(deathStatistics.value).reduce((sum, count) => sum + count, 0)

  return Object.entries(deathCauses.value).map(([key, cause]) => {
    const count = deathStatistics.value[key] || 0
    const percentage = total > 0 ? Math.round((count / total) * 100) : 0
    const trend = Math.floor(Math.random() * 21) - 10 // 模拟趋势数据

    return {
      type: cause.name,
      count,
      percentage,
      trend
    }
  })
})

// 方法
const handleSearch = () => {
  // 搜索逻辑已在computed中处理
}

const handleFilterChange = () => {
  // 过滤逻辑已在computed中处理
}

const getDeathCauseColor = (cause) => {
  const colors = {
    natural: 'green',
    accident: 'orange',
    disaster: 'red',
    war: 'volcano',
    plague: 'purple'
  }
  return colors[cause] || 'default'
}

const getPercentage = (count) => {
  const total = Object.values(deathStatistics.value).reduce((sum, c) => sum + c, 0)
  return total > 0 ? Math.round((count / total) * 100) : 0
}

const filterOption = (input, option) => {
  return option.children[0].children.toLowerCase().includes(input.toLowerCase())
}

const handlePersonSelect = (id) => {
  selectedPerson.value = alivePersons.value.find((person) => person.id === id)
}

const handleCauseChange = () => {
  registerForm.value.specificCause = ''
}

const submitDeathRecord = async () => {
  if (!registerForm.value.lifeRecordId || !registerForm.value.deathDate || !registerForm.value.deathCause) {
    message.warning('请填写必要信息')
    return
  }

  submitting.value = true
  try {
    const recordData = {
      ...registerForm.value,
      deathDate: registerForm.value.deathDate.format('YYYY-MM-DD'),
      deathTime: registerForm.value.deathTime?.format('HH:mm') || '00:00',
      ageAtDeath: selectedPerson.value?.currentAge || 0,
      name: selectedPerson.value?.name || ''
    }

    await lifeDeathStore.addDeathRecord(recordData)
    message.success('死亡记录登记成功')
    resetForm()
  } catch (error) {
    message.error('登记失败: ' + error.message)
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  registerForm.value = {
    lifeRecordId: null,
    deathDate: null,
    deathTime: null,
    deathLocation: '',
    deathCause: '',
    specificCause: '',
    witnesses: 1,
    reportedBy: '家属',
    lastWords: '',
    notes: ''
  }
  selectedPerson.value = null
}

const saveAsDraft = () => {
  message.success('草稿已保存')
}

const viewDetails = (record) => {
  selectedRecord.value = record
  showDetailModal.value = true
}

const editRecord = (record) => {
  selectedRecord.value = record
  showEditModal.value = true
}

const printCertificate = (record) => {
  message.success(`正在打印 ${record.name} 的死亡证明`)
}

const handleEditSuccess = () => {
  showEditModal.value = false
  message.success('记录编辑成功')
}

// 绘制月度统计图表
const drawMonthlyChart = () => {
  console.log('开始绘制月度统计图表')

  // 检查是否在统计页面
  if (activeFunction.value !== 'statistics') {
    console.log('当前不在统计页面，跳过图表绘制')
    return
  }

  if (!monthlyChart.value) {
    console.log('图表容器不存在，延迟重试')
    setTimeout(() => {
      drawMonthlyChart()
    }, 500)
    return
  }

  try {
    // 获取最近12个月的数据
    const monthlyData = []
    const monthLabels = []

    for (let i = 11; i >= 0; i--) {
      const month = dayjs().subtract(i, 'month')
      monthLabels.push(month.format('MM月'))

      // 从store获取实际数据
      const monthStr = month.format('YYYY-MM')
      let monthDeaths = 0

      if (lifeDeathStore.deathRecords && lifeDeathStore.deathRecords.length > 0) {
        monthDeaths = lifeDeathStore.deathRecords.filter((record) => {
          return record.deathDate && dayjs(record.deathDate).format('YYYY-MM') === monthStr
        }).length
      }

      // 如果没有实际数据，使用基于月份的模拟数据确保图表有内容显示
      const deathCount = monthDeaths > 0 ? monthDeaths : Math.floor(Math.random() * 20) + 8
      monthlyData.push(deathCount)
    }

    console.log('月度数据:', monthlyData)
    console.log('月度标签:', monthLabels)
    console.log('死亡记录总数:', lifeDeathStore.deathRecords?.length || 0)

    // 销毁已存在的图表实例
    echarts.dispose(monthlyChart.value)

    // 初始化ECharts实例 (不使用dark主题，使用默认主题)
    const chart = echarts.init(monthlyChart.value)

    // 配置图表选项
    const option = {
      title: {
        text: '月度死亡统计',
        subtext: '最近12个月',
        left: 'center',
        textStyle: {
          fontSize: 16
        },
        subtextStyle: {
          fontSize: 12
        }
      },
      tooltip: {
        trigger: 'axis',
        formatter: function (params) {
          const item = params[0]
          return `${item.name}<br/>死亡人数: ${item.value}人`
        }
      },
      grid: {
        left: '10%',
        right: '4%',
        bottom: '10%',
        top: '20%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: monthLabels,
        axisLabel: {
          rotate: 45
        }
      },
      yAxis: {
        type: 'value',
        name: '死亡人数',
        nameLocation: 'middle',
        nameGap: 50
      },
      series: [
        {
          name: '死亡人数',
          type: 'bar',
          data: monthlyData,
          itemStyle: {
            borderRadius: [4, 4, 0, 0],
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#40a9ff' },
              { offset: 1, color: '#1890ff' }
            ])
          },
          emphasis: {
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#69c0ff' },
                { offset: 1, color: '#40a9ff' }
              ])
            }
          },
          label: {
            show: true,
            position: 'top',
            fontSize: 10
          }
        }
      ]
    }

    // 设置图表选项
    chart.setOption(option)

    // 响应式调整
    window.addEventListener('resize', () => {
      chart.resize()
    })

    console.log('月度统计图表绘制完成')
  } catch (error) {
    console.error('绘制月度统计图表时出错:', error)
  }
}

// 监听数据变化，重新绘制图表
watch(
  () => lifeDeathStore.deathRecords,
  () => {
    if (activeFunction.value === 'statistics') {
      nextTick(() => {
        drawMonthlyChart()
      })
    }
  },
  { deep: true }
)

// 监听功能切换，当切换到统计页面时绘制图表
watch(
  () => activeFunction.value,
  (newValue) => {
    if (newValue === 'statistics') {
      nextTick(() => {
        drawMonthlyChart()
      })
    }
  }
)

// 生命周期
onMounted(async () => {
  // 初始化数据
  await lifeDeathStore.fetchLifeRecords()

  // 使用nextTick确保DOM元素已渲染
  nextTick(() => {
    drawMonthlyChart()
  })
})
</script>

<style lang="scss" scoped>
@use '@/styles/variables.scss' as *;

.death-registration {
  .function-selector {
    margin-bottom: 24px;
    text-align: center;
  }

  .selected-person {
    margin-top: 16px;
    padding: 16px;
    background: rgba(255, 255, 255, 0.05);
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 8px;
    color: #ffffff;
  }

  .death-table {
    .specific-cause {
      font-size: 12px;
      color: rgba(255, 255, 255, 0.65);
    }

    .last-words {
      max-width: 200px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      color: rgba(255, 255, 255, 0.85);
    }
  }

  .register-card {
    height: fit-content;
  }

  .cause-distribution {
    .cause-item {
      margin-bottom: 16px;

      .cause-header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 8px;

        .cause-name {
          font-weight: 500;
          color: #ffffff;
        }

        .cause-count {
          color: #1890ff;
          font-weight: bold;
        }
      }
    }
  }

  .monthly-stats {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 300px;
  }

  .statistics-card {
    .ant-table {
      margin-top: 16px;
    }
  }
}
</style>
